package com.fanqwz.kotlinmvvm.di.module

import com.fanqwz.kotlinmvvm.common.util.log.HttpLogger
import com.fanqwz.kotlinmvvm.common.util.rxjava.gson.*
import com.fanqwz.kotlinmvvm.data.web.iface.Backend
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
import kotlin.reflect.jvm.internal.impl.load.kotlin.JvmType

/**
 * Created by fanqwz on 2017/10/26.
 */
@Module
class NetWorkModule {
    @Provides
    @Singleton
    fun getHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
                .addInterceptor(HttpLogger())
                .build()
    }

    @Provides
    @Singleton
    fun getRetrofit(httpClient: OkHttpClient): Retrofit.Builder {
        return Retrofit.Builder()
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
//                        .serializeNulls()
                        .registerTypeAdapter(JvmType.Object::class.java, GsonNullDeserializer())
                        .registerTypeAdapter(Any::class.java, GsonNullDeserializer())
                        .registerTypeAdapter(Int::class.java, IntegerDefault0Adapter())
                        .registerTypeAdapter(Int::class.javaPrimitiveType, IntegerDefault0Adapter())
                        .registerTypeAdapter(Double::class.java, DoubleDefault0Adapter())
                        .registerTypeAdapter(Double::class.javaPrimitiveType, DoubleDefault0Adapter())
                        .registerTypeAdapter(Long::class.java, LongDefault0Adapter())
                        .registerTypeAdapter(Long::class.javaPrimitiveType, LongDefault0Adapter())
                        .registerTypeAdapter(List::class.java, GsonArrayNullAdapter<Any>()).create()))
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    }

    @Provides
    @Singleton
    fun getBackend(builder: Retrofit.Builder): Backend {
        return builder.baseUrl(Backend.BASE_URL)
                .build()
                .create(Backend::class.java)
    }
}